package com.eastone.user.serverapi.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.eastone.user.serverapi.listener.SessionContext;
import com.yjx.framework.cache.ServiceResultCodeCache;
import com.yjx.framework.util.JsonUtil;

public class AuthFilter implements Filter {
	private static final Logger LOG = LogManager.getLogger(AuthFilter.class);
	private static ServiceResultCodeCache resultCode = ServiceResultCodeCache.getInstance();

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = null;

		boolean doFilter = filterUrl(request);
		if (doFilter) {
			String sessionId = (String) req.getParameter("sessionId");
			if("sessionId".equals(sessionId)){
				chain.doFilter(req, resp);
				return;
			}
			if (LOG.isDebugEnabled()) {
				LOG.debug("sessionId:" + sessionId);
				LOG.debug("session:" + SessionContext.getInstance().getSessionMap().get(sessionId));
			}
			if (!SessionContext.getInstance().getSessionMap().keySet().contains(sessionId)) {
				// 转登录页面
				out = response.getWriter();
				out.println(JsonUtil.getResultJsonObject(resultCode.get("common.illegal.request"), "非法访问"));
				return;
			}
		}

		chain.doFilter(req, resp);

	}

	/**
	 * 是否过滤url
	 * 
	 * @param request
	 * @return
	 */
	private boolean filterUrl(HttpServletRequest request) {
		String[] notFilter = new String[] { "/infoUser/login", "/check/sign", "/oauth/" };
		String uri = request.getRequestURI();
		boolean doFilter = true;
		for (String s : notFilter) {
			if (uri.indexOf(s) != -1) {
				doFilter = false;
				break;
			}
		}
		return doFilter;
	}

	public void destroy() {
	}
}
